package com.gopay.bis.ccb.bcdl.operation;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.domain.bank.ccb.bcdl.BaseResBody;
import com.gopay.common.domain.bank.ccb.bcdl.BaseReqBody;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.mapper.MapperWrapper;

public class CcbBcdlBaseHelper<T extends BaseResBody> {
	protected final static Logger logger = LoggerFactory.getLogger("BANK_LOG");
	
	private Class<T> entityClass;
	
	public CcbBcdlBaseHelper(){
		Type genType = getClass().getGenericSuperclass();  
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
        entityClass = (Class) params[0];
	}
	
	protected String getXml(BaseReqBody req){
		XStream xstream = buildBase();  
        String xml = xstream.toXML(req);
		return xml;
	}
	
	protected XStream buildBase(){
		XStream xstream = new XmlDeclarationXStream(new XppDriver(new NoNameCoder()));  
        xstream.autodetectAnnotations(true);
        xstream.aliasSystemAttribute(null, "class");
        xstream.setMode(XStream.NO_REFERENCES);
        return xstream;
	}
	
	public T parse(String xml){
//		XStream xs = new XStream(new DomDriver());
		XStream xs = new XStream() {
			@Override
			protected MapperWrapper wrapMapper(MapperWrapper next) {
				return new MapperWrapper(next) {
					@Override
					public boolean shouldSerializeMember(Class definedIn,
							String fieldName) {
						if (definedIn == Object.class) {
							return false;
						}
						return super
								.shouldSerializeMember(definedIn, fieldName);
					}
				};
			}
		};
        xs.processAnnotations(entityClass);
        xs.autodetectAnnotations(true);
        T body = (T) xs.fromXML(xml);
        return body;
	}
}
